package cn.tedu.rebbimq.m2_work;

import com.rabbitmq.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;


public class Consumer {
    private static final Logger log =  LoggerFactory.getLogger(Consumer.class);
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setUsername("admin");
        f.setPassword("admin");
        f.setVirtualHost("/ryan");
        Connection con = f.newConnection();
        Channel c = con.createChannel();
        // 2.定义队列 helloWord
//        c.queueDeclare(
//                "helloword",
//                true,
//                false,
//                false,
//                null
//        );

        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                String msg = new String(delivery.getBody());
                System.out.println("收到: "+msg);

                for(int i= 0; i<msg.length();i++){
                    if(msg.charAt(i) == '.'){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

                c.basicQos(1);
                c.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
                System.out.println("消息处理结束.");

            }
        };

        CancelCallback cancelCallback = new CancelCallback(){

            @Override
            public void handle(String s) throws IOException {

            }
        };

        // 3接收数据
        c.basicConsume(
                "helloworld",
                true,
                deliverCallback,
                cancelCallback
        );
    }
}
